package com.x.uikit.channel.multitabs;

import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;

public class DefaultIndicator implements ScrollableTabLayout.IIndicator {
    private final Interpolator IN_INTERPOLATOR = easeInQuad();
    private final Interpolator OUT_INTERPOLATOR = easeOutQuad();
    private RectF rectF;
    private int tabWidth;
    private int indicatorHeight;
    private float indicatorRadius;
    private Paint rectPaint;

    public DefaultIndicator() {
        init();
    }

    private void init() {

        rectF = new RectF();
        rectPaint = new Paint();
        rectPaint.setColor(0x9f0000ff);
        tabWidth = ScrollableTabLayout.dpI(50);
        indicatorHeight = ScrollableTabLayout.dpI(4);
        indicatorRadius = ScrollableTabLayout.dpI(2);
    }

    @Override
    public void onDraw(Canvas canvas, ViewGroup tabContainer, int currentPosition, int lastPosition, float currentPositionOffset) {

        final int height = tabContainer.getHeight();
        View lastTab = tabContainer.getChildAt(lastPosition);
        View currentTab = tabContainer.getChildAt(currentPosition);
        rectF.left = getTabRight(lastTab) - lastTab.getWidth() / 2f - tabWidth / 2f;
        rectF.right = rectF.left + tabWidth;
        rectF.top = height - indicatorHeight;
        rectF.bottom = height;
        float distance = (getTabRight(currentTab) - currentTab.getWidth() / 2) - (getTabRight(lastTab) - lastTab.getWidth() / 2);
        float offsetLeft = IN_INTERPOLATOR.getInterpolation(currentPositionOffset);
        float offsetRight = OUT_INTERPOLATOR.getInterpolation(currentPositionOffset);
        if (currentPosition > lastPosition) {
            rectF.left += distance * offsetLeft;
            rectF.right += distance * offsetRight;
        } else {
            rectF.left += distance * offsetRight;
            rectF.right += distance * offsetLeft;
        }
        if (rectF.right - rectF.left > tabWidth + tabWidth) {
            rectF.right = rectF.left + tabWidth + tabWidth;
        }
        canvas.drawRoundRect(rectF, indicatorRadius, indicatorRadius, rectPaint);

    }

    private int getTabRight(View tab) {
        return tab.getRight();
    }

    static Interpolator easeInQuad() {
        return new Interpolator() {
            @Override
            public float getInterpolation(float input) {
                return input * input;
            }
        };
    }

    static Interpolator easeOutQuad() {
        return new Interpolator() {
            @Override
            public float getInterpolation(float input) {
                return -input * (input - 2f);
            }
        };
    }
}
